package videostoreapp.dataobjects;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import videostoreapp.Customer;
import videostoreapp.Constants;

public class CustomerDO implements Customer {

	Connection conn = null; 
	PreparedStatement 
		psCreateCust = null, 
		psUpdCust = null,
		psDelCust = null,
		psGetCust = null;
	
	public CustomerDO(){
		try {
			conn = Constants.getConnection();
			
			psCreateCust = conn.prepareStatement(
					"INSERT INTO Customers (name, address) VALUES (?, ?)",
					Statement.RETURN_GENERATED_KEYS);
			
			psUpdCust = conn.prepareStatement(
					"UPDATE Customers SET name = ?, address = ? WHERE ID = ?");
			
			psDelCust = conn.prepareStatement(
					"DELETE FROM Customers WHERE ID = ?");
			
			psGetCust = conn.prepareStatement(
					"SELECT name, address FROM Customers WHERE ID = ?");
			
		} catch (SQLException e) {
			Constants.SQLExceptionHandler(e);
		}
	}
	 
	public int createCustomer(CustomerInfo cinfo) {
		int custId = -1;
		if(cinfo != null){
			try{
				psCreateCust.setString(1, cinfo.name);
				psCreateCust.setString(2, cinfo.address);
				if(psCreateCust.executeUpdate() >0){
					ResultSet rs = psCreateCust.getGeneratedKeys();
					if(rs.next()){
						custId = rs.getInt(1);
					}		
					rs.close();
				}

			}catch(SQLException sqe){
				Constants.SQLExceptionHandler(sqe);
			}
		}
		return custId;
	}

	public void deleteCustomer(int id) {
		try{
			psDelCust.setInt(1, id);
			psDelCust.executeUpdate();
			
		}catch(SQLException sqe){
			Constants.SQLExceptionHandler(sqe);
		}
		
	}

	public CustomerInfo getCustomerById(int id) {
		CustomerInfo cif = null;
		try{
			psGetCust.setInt(1, id);
			ResultSet rs = psGetCust.executeQuery();
			if(rs.next()){
				cif = new CustomerInfo(
						id,
					rs.getString("name"),
					rs.getString("address")
				);
				
			}
			rs.close();
		}catch(SQLException sqe){
			Constants.SQLExceptionHandler(sqe);
		}
		return cif;
	}

	public void modifyCustomer(CustomerInfo cinfo) {
		if(cinfo == null) return;
		
		try{
			psUpdCust.setString(1, cinfo.name);
			psUpdCust.setString(2, cinfo.address);
			psUpdCust.setInt(3, cinfo.id);
			psUpdCust.executeUpdate();
			
		}catch(SQLException sqe){
			Constants.SQLExceptionHandler(sqe);
		}
		
	}


}
